import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import { fileURLToPath } from "url";
// https://devtools.vuejs.org/getting-started/introduction
import vueDevTools from "vite-plugin-vue-devtools";

//element-plus自动导入
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

function resolvePath(paths: string) {
  return path.resolve(__dirname, paths);
}

// https://vite.dev/config/
export default ({ mode }: { mode: string }) => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  return defineConfig({
    plugins: [
      vue(),
      vueDevTools(), // 自动导入 components 下面的组件，无需 import 引入
      Components({
        deep: true,
        extensions: ["vue"],
        dirs: ["src/components"], // 自动导入的组件目录
        resolvers: [ElementPlusResolver()],
        dts: "src/types/components.d.ts", // 指定类型声明文件的路径
      }),
      AutoImport({
        imports: ["vue", "vue-router", "@vueuse/core", "pinia"],
        resolvers: [ElementPlusResolver()],
        dts: "src/types/auto-imports.d.ts",
        eslintrc: {
          // 这里先设置成true然后pnpm dev 运行之后会生成 .auto-import.json 文件之后，在改为false
          enabled: true,
          filepath: "./.auto-import.json",
          globalsPropValue: true,
        },
      }),
    ],
    // 路径别名
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
        "@modules": resolvePath("src/modules"),
        "@imgs": resolvePath("src/assets/img"),
        "@icons": resolvePath("src/assets/icons"),
        "@utils": resolvePath("src/utils"),
        "@stores": resolvePath("src/stores"),
        "@plugins": resolvePath("src/plugins"),
        "@styles": resolvePath("src/assets/styles"),
      },
    },
    server: {
      port: Number(env.VITE_PORT),
      open: true, //运行后自动开启浏览器
      proxy: {
        "/api": {
          target: "",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
      host: true,
    },
    // 预加载项目必需的组件
    optimizeDeps: {
      include: ["vue", "vue-router", "pinia"],
    },
    css: {
      preprocessorOptions: {
        // sass variable and mixin
        scss: {
          additionalData: `
            @use "@styles/variables.scss" as *; @use "@styles/mixin.scss" as *;
          `,
        },
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: "internal:charset-removal",
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === "charset") {
                  atRule.remove();
                }
              },
            },
          },
        ],
      },
    },
  });
};
